package com.atguigu.juc.study.chapter09.atomics;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author : leimingchao
 * @date Date : 2022年06月15日 23:28
 */
public class MyVar {

    public volatile Boolean isInit = Boolean.FALSE;

    AtomicReferenceFieldUpdater<MyVar, Boolean> fieldUpdater = AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");

    public void init(MyVar myVar) {

        if (fieldUpdater.compareAndSet(myVar, Boolean.FALSE, Boolean.TRUE)) {

            System.out.println(Thread.currentThread().getName() + "\t" + "--start init,need 2 seconds");

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "-- over init");

        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "---- 已经有线程在进行初始化工作。。。。。");
        }
    }
}
